﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;
using Corona.TagContract;
using Corona.TagToolkit.Exception;

namespace Corona.TagToolkit
{


    /// <summary>
    /// 数据库操作对象，维护强连接
    /// StrongLink表中存的是
    /// </summary>
    /// <typeparam name="T">资源类型</typeparam>
    public class StrongLinkDAO<T>:IDisposable
    {
        DbProviderFactory dbFactory;
        DbConnection conn;
        
        /// <summary>
        /// 由uid获得资源描述符s
        /// 因为一个uid可能有多个实际对应资源
        /// </summary>
        /// <param name="uid">资源的uid</param>
        /// <returns>可被STconverter转换为资源的字符串组</returns>
        internal List<string> GetLocazier(long uid)
        {
            //DataRow[] datarows = StrongLink.Select("uid=" + uid.ToString());
            //string[] resault = new string[datarows.Rank];
            //for (int i = 0; i < datarows.Rank; i++)
            //    resault[i] = (string)datarows[i]["resource"];
            //return resault;
            List<string> resultList = new List<string>();
            String sql = "SELECT ResourceString FROM Tag WHERE Uid = '" + uid.ToString() + "'";
            DbCommand cmd = GetDbCommand();
            cmd.CommandText = sql;
            DbDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
                resultList.Add(reader[0].ToString());
            cmd.Dispose();
            reader.Close();
            return resultList;
        }
        /// <summary>
        /// 由资源获得其uid
        /// </summary>
        /// <param name="resource"></param>
        /// <returns></returns>
        internal long getUid(Resource<T> resource)
        {

                long uid = -1;
                String sql = "SELECT Uid FROM Tag WHERE ResourceString ='" + resource.Locazier+"'";
                DbCommand cmd = GetDbCommand();
                cmd.CommandText = sql;
                DbDataReader reader = cmd.ExecuteReader();
                if (reader.Read())
                    uid = long.Parse(reader[0].ToString());
                cmd.Dispose();
                reader.Close();
                return uid;
            



        }
        internal void addStrongLink(Resource<T> resource, long uid)
        { //TODO
            String sql = "INSERT INTO Tag VALUES('" + uid.ToString() + "','" + resource.Locazier + "')";
            DbCommand cmd = GetDbCommand();
            cmd.CommandText = sql;
            try
            {
                cmd.ExecuteNonQuery();
                cmd.Dispose();
            }
            catch (InvalidOperationException ex)
            {
                System.Console.WriteLine(ex.Message);
            }
        }

        internal void removeStrongLink(Resource<T> resource)
        { //TODO
            if (resource.State == ResourceState.Controlled)
            {
                string sql = "DELETE FROM Tag WHERE ResourceString ='" + resource.Locazier + "'";
                DbCommand cmd = GetDbCommand();
                cmd.CommandText = sql;
                try
                {
                    cmd.ExecuteNonQuery();
                    cmd.Dispose();
                }
                catch (InvalidOperationException ex)
                {
                    System.Console.WriteLine(ex.Message);
                }
            }
        }
        /// <summary>
        /// 初始化数据库
        /// </summary>
        internal StrongLinkDAO<T> init(string connectionString,string dbProviderName)
        {
            dbFactory = DbProviderFactories.GetFactory(dbProviderName);
            conn = this.GetDatabaseConnection(connectionString);
            conn.Open();
            return this;
        }
        public DbConnection GetDatabaseConnection(string connectionString)
        {
            
            DbConnection conn = dbFactory.CreateConnection();
            conn.ConnectionString = connectionString;
            return conn;
        }
        public DbCommand GetDbCommand()
        {
            DbCommand command = dbFactory.CreateCommand();
            command.Connection = conn;
            return command;
        }

        #region IDisposable Members

        public void Close()
        {
            ((IDisposable)this).Dispose();
        }


        void IDisposable.Dispose()
        {
            DisposeConnection(true);
            GC.SuppressFinalize(this);
        }



        ~StrongLinkDAO()
        {
            DisposeConnection(false);
        }

        protected virtual void DisposeConnection(bool isDisposing)
        {
            if (isDisposing && conn.State == ConnectionState.Open )
                conn.Close();

        }

        #endregion
    }
}
